/*
 * Copyright (c) 2011-2023, baomidou (jobob@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dromara.common.mybatis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.override.MybatisMapperProxy;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.core.toolkit.reflect.GenericTypeUtils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.binding.Binder;
import org.dromara.common.mybatis.core.domain.BaseEntity;
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;
import org.dromara.common.mybatis.core.page.CustomConditions;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.service.IService;
import org.dromara.common.mybatis.utils.QueryWrapperUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.SqlSessionUtils;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * IService 实现类（ 泛型：M 是 mapper 对象，T 是实体 ）
 *
 * @author hubin
 * @since 2018-06-23
 */
@SuppressWarnings("unchecked")
public class ServiceImpl<M extends BaseMapperPlus<T, VO>, T extends BaseEntity, BO, VO> implements IService<T, BO, VO> {

    private final ConversionService conversionService = DefaultConversionService.getSharedInstance();

    protected final Log log = LogFactory.getLog(getClass());

    @Autowired
    protected M baseMapper;

    protected final Class<?>[] typeArguments = GenericTypeUtils.resolveTypeArguments(getClass(), ServiceImpl.class);

    @Override
    public M getBaseMapper() {
        return baseMapper;
    }

    protected final Class<T> entityClass = currentModelClass();

    @Override
    public Class<T> getEntityClass() {
        return entityClass;
    }

    protected final Class<M> mapperClass = currentMapperClass();

    private volatile SqlSessionFactory sqlSessionFactory;

    @SuppressWarnings({"rawtypes", "deprecation"})
    protected SqlSessionFactory getSqlSessionFactory() {
        if (this.sqlSessionFactory == null) {
            synchronized (this) {
                if (this.sqlSessionFactory == null) {
                    Object target = this.baseMapper;
                    // 这个检查目前看着来说基本上可以不用判断Aop是不是存在了.
                    if (com.baomidou.mybatisplus.extension.toolkit.AopUtils.isLoadSpringAop()) {
                        if (AopUtils.isAopProxy(this.baseMapper)) {
                            target = AopProxyUtils.getSingletonTarget(this.baseMapper);
                        }
                    }
                    if (target != null) {
                        MybatisMapperProxy mybatisMapperProxy = (MybatisMapperProxy) Proxy.getInvocationHandler(target);
                        SqlSessionTemplate sqlSessionTemplate = (SqlSessionTemplate) mybatisMapperProxy.getSqlSession();
                        this.sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
                    } else {
                        this.sqlSessionFactory = GlobalConfigUtils.currentSessionFactory(this.entityClass);
                    }
                }
            }
        }
        return this.sqlSessionFactory;
    }


    protected Class<M> currentMapperClass() {
        return (Class<M>) this.typeArguments[0];
    }

    protected Class<T> currentModelClass() {
        return (Class<T>) this.typeArguments[1];
    }

    /**
     * 更新前的数据校验
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean validEntityBeforeUpdate(T entity) {
        //TODO 做一些数据校验,如唯一约束
        return true;
    }

    /**
     * 保存前的数据校验
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean validEntityBeforeSave(T entity) {
        //TODO 做一些数据校验,如唯一约束
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean validEntityBeforeDelete(Collection<Long> ids) {
        //TODO 做一些数据校验,如唯一约束
        return true;
    }

    /**
     * 新增红包
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(BO bo) {
        T add = MapstructUtils.convert(bo, getEntityClass());
        boolean flag = validEntityBeforeSave(add);
        if (!flag) {
            return flag;
        }
        flag = baseMapper.insert(add) > 0;
        if (flag) {
            BeanUtil.setProperty(bo, "id", BeanUtil.getProperty(add, "id"));
        }
        return flag;
    }

    /**
     * 修改红包
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(BO bo) {
        T update = MapstructUtils.convert(bo, getEntityClass());

        boolean flag = validEntityBeforeUpdate(update);
        if (!flag) {
            return flag;
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 删除页面
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidById(Long id, Boolean isValid) {
        return deleteWithValidByIds(CollUtil.newHashSet(id), isValid);
    }

    /**
     * 批量删除红包
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            validEntityBeforeDelete(ids);
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    /**
     * 查询红包
     */
    @Override
    @Transactional(readOnly = true)
    public VO getOne(BO bo, Function<LambdaQueryWrapper<T>, Boolean>
        func) {
        LambdaQueryWrapper<T> lqw = buildQueryWrapper(bo);
        func.apply(lqw);
        lqw.last("limit 0 offset 1");
        VO entity = this.baseMapper.selectVoOne(lqw);
        if (entity == null) {
            return entity;
        }
        return fill(entity);
    }

    /**
     * 查询红包次数
     */
    @Override
    @Transactional(readOnly = true)
    public Long count(QueryWrapper<T> wrapper) {

        wrapper.last("limit 0 offset 1");
        Long count = this.baseMapper.selectCount(wrapper);
        return count;
    }

    @Override
    public Long count(LambdaQueryWrapper<T> wrapper) {
        wrapper.last("limit 0 offset 1");
        Long count = this.baseMapper.selectCount(wrapper);
        return count;
    }

    /**
     * 查询红包
     */
    @Override
    @Transactional(readOnly = true)
    public VO getOne(QueryWrapper<T> wrapper) {

        wrapper.last("limit 0 offset 1");
        VO entity = this.baseMapper.selectVoOne(wrapper);
        if (entity == null) {
            return entity;
        }
        return fill(entity);
    }

    @Override
    public VO getOne(LambdaQueryWrapper<T> wrapper) {
        wrapper.last("limit 0 offset 1");
        VO entity = this.baseMapper.selectVoOne(wrapper);
        if (entity == null) {
            return entity;
        }
        return fill(entity);
    }

    /**
     * 查询红包
     */
    @Override
    @Transactional(readOnly = true)
    public VO getOne(BO bo) {

        return getOne(bo, lambdaQueryWrapper -> true);
    }

    /**
     * 查询红包
     */
    @Override
    @Transactional(readOnly = true)
    public VO queryById(Serializable id) {
        VO entity = baseMapper.selectVoById(id);
        if (entity == null) {
            return entity;
        }
        return fill(entity);
    }


    /**
     * 查询红包列表
     */
    @Override
    @Transactional(readOnly = true)
    public TableDataInfo<VO> queryPageList(BO bo, PageQuery pageQuery) {

        return queryPageList(bo, pageQuery, lambdaQueryWrapper -> true);
    }

    /**
     * 查询红包列表
     */
    @Override
    @Transactional(readOnly = true)
    public TableDataInfo<VO> queryPageList(BO bo, PageQuery pageQuery,
                                           Function<LambdaQueryWrapper<T>, Boolean>
                                               func) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<T> lqw = buildQueryWrapper(queryWrapper.lambda(), bo);
        func.apply(lqw);
        Page<VO> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<VO> list = result.getRecords();
        List<VO> newList = new ArrayList<>();
        list.forEach(entity -> {
            newList.add(fill(entity));
        });
        result.setRecords(newList);
        return TableDataInfo.build(result);
    }


    /**
     * 查询列表
     */
    @Override
    @Transactional(readOnly = true)
    public List<VO> queryList(QueryWrapper<T> wrapper) {
        List<VO> list = baseMapper.selectVoList(wrapper);
        if (list == null) {
            return new ArrayList<VO>();
        }
        list.forEach(entity -> {
            fill(entity);
        });
        return list;
    }


    /**
     * 查询列表
     */
    @Override
    @Transactional(readOnly = true)
    public List<VO> queryList(LambdaQueryWrapper<T> wrapper) {
        List<VO> list = baseMapper.selectVoList(wrapper);
        if (list == null) {
            return new ArrayList<VO>();
        }
        list.forEach(entity -> {
            fill(entity);
        });
        return list;
    }

    /**
     * 查询红包列表
     */
    @Override
    @Transactional(readOnly = true)
    public List<VO> queryList(BO bo) {
        return queryList(bo, lambdaQueryWrapper -> true);
    }

    /**
     * 查询红包列表
     */
    @Override
    @Transactional(readOnly = true)
    public List<VO> queryList(BO bo,
                              Function<LambdaQueryWrapper<T>, Boolean>
                                  func) {
        LambdaQueryWrapper<T> lqw = buildQueryWrapper(bo);
        func.apply(lqw);
        List<VO> list = baseMapper.selectVoList(lqw);
        if (list == null) {
            return new ArrayList<VO>();
        }
        list.forEach(entity -> {
            fill(entity);
        });
        return list;
    }

    public VO fill(VO entity) {
        return entity;
    }

    public LambdaQueryWrapper<T> buildQueryWrapper(BO bo) {
        LambdaQueryWrapper<T> lqw = Wrappers.lambdaQuery();

        return buildQueryWrapper(lqw, bo);
    }

    public LambdaQueryWrapper<T> buildQueryWrapper(LambdaQueryWrapper<T> lqw, BO bo) {
        return lqw;
    }
}
